/**
 * @Author: ZFEason
 * @Date: 2023-07-11 14:00:01
 * @LastEditors: ZFEason
 * @LastEditTime: 2023-07-20 17:30:46
 * @FilePath: /ift-economy-network-h5/src/pages/storage-situation/AddProject/index.tsx
 * @Description:
 */

import { useEffect, useMemo, useState } from "react";
import {
  Button,
  Checkbox,
  DatePicker,
  Form,
  Input,
  Picker,
  Space,
  TextArea,
  Image,
  Toast,
} from "antd-mobile";
import dayjs from "dayjs";
import { useNavigate } from "react-router-dom";
import Styles from "./index.module.less";
import rightArrow from "@/assets/image/right_arrow.png";
import {
  addExcavateProject,
  getLeaderUnitList,
  getStreetList,
} from "@/service/storage-situation";
import FormUpload from "../Components/FormUpload";
import { CloseCircleOutline } from "antd-mobile-icons";

const Index: React.FC<any> = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const [detailData, setDetailData] = useState<any>({ defaultValue: [] });

  const [pickerVisible, setPickerVisible] = useState(false);
  const [walkTimeVisible, setWalkTimeVisible] = useState(false);
  const [startTimeVisible, setStartTimeVisible] = useState(false);
  const [warehousingTimeVisible, setWarehousingTimeVisible] = useState(false);
  const [leaderList, setLeaderList] = useState([
    { label: "福田区发改局", value: "福田区发改局" },
    { label: "福田区科创局", value: "福田区科创局" },
    { label: "福田区工信局", value: "福田区工信局" },
    { label: "福田区文广旅体局", value: "福田区文广旅体局" },
    { label: "福田区金融局", value: "福田区金融局" },
  ]);
  const [streetList, setStreetList] = useState([
    { label: "福田区发改局", value: "福田区发改局" },
    { label: "福田区科创局", value: "福田区科创局" },
    { label: "福田区工信局", value: "福田区工信局" },
    { label: "福田区文广旅体局", value: "福田区文广旅体局" },
    { label: "福田区金融局", value: "福田区金融局" },
  ]);

  // 提交
  const onFinish = async (values: any) => {
    console.log(
      "onFinish---",
      values,
      dayjs().format("YYYY-MM-DD"),
      dayjs(values.visitTime).format("YYYY-MM-DD"),
      dayjs(values.startTime).format("YYYY-MM-DD"),
      dayjs(values.predictTime).format("YYYY-MM-DD"),
      detailData.defaultValue
    );
    const params = { ...values };
    const res: any = await addExcavateProject(params);
    if (res?.code === 0) {
      Toast.show("已提交申请");
      navigate(-1);
    }
  };

  // 表格自定义校验
  const checkTableRule = (_: any, value: []) => {
    const isTrue = (value ?? []).some((item: []) => item.every(Boolean));

    if (isTrue) {
      return Promise.resolve();
    }
    return Promise.reject(new Error("至少填写一年"));
  };

  const fetchLeaderList = async () => {
    const res: any = await getLeaderUnitList();
    const list =
      res?.data?.list?.map((item: any) => ({
        label: item.name,
        value: item.name,
      })) ?? [];
    res?.code === 0 && setLeaderList(list);
  };

  const fetchStreetList = async () => {
    const res: any = await getStreetList();
    const list =
      res?.data?.list?.map((item: any) => ({
        label: item.name,
        value: item.name,
      })) ?? [];
    res?.code === 0 && setStreetList(list);
  };

  useEffect(() => {
    fetchLeaderList();
  }, []);

  return (
    <>
      <Form
        layout="horizontal"
        // mode="card"
        form={form}
        onFinish={onFinish}
        onValuesChange={(_, allValues) => {
          setDetailData((state: any) => {
            state = { ...allValues };
            return state;
          });
        }}
        className={`${Styles.form}`}
        footer={
          <div
            className={`bg_ffffff d_between_center ${Styles.footer_container} p_l_r_16`}
          >
            <Button
              className={Styles.submit_btn}
              block
              type="submit"
              color="primary"
              size="large"
            >
              提交
            </Button>

            <Button
              className={Styles.cancel_btn}
              block
              type="button"
              color="primary"
              size="large"
              onClick={() => navigate(-1)}
            >
              退出编辑
            </Button>
          </div>
        }
      >
        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}>基本信息</span>
        </Form.Header>
        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.visitTime !== curValues.visitTime
          }
          noStyle
        >
          {() => (
            <Form.Item
              name="visitTime"
              label="走访时间"
              rules={[
                {
                  required: false,
                  message: "走访时间不能为空",
                },
              ]}
              trigger="onConfirm"
              onClick={() => setWalkTimeVisible(true)}
            >
              <DatePicker
                // precision="month"
                visible={walkTimeVisible}
                onClose={() => setWalkTimeVisible(false)}
              >
                {(value, actions) => (
                  <>
                    {value ? (
                      <span
                        className={`fontsize_14 fw_400 color_333`}
                        onClick={actions.open}
                      >
                        {dayjs(value).format("YYYY-MM-DD")}
                      </span>
                    ) : (
                      <span className={`fontsize_14 fw_500 color_666`}>
                        请选择
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </>
                )}
              </DatePicker>
            </Form.Item>
          )}
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.takeDepartment !== curValues.takeDepartment
          }
          noStyle
        >
          {({ getFieldValue }) => (
            <Form.Item
              name="takeDepartment"
              label="牵头单位"
              rules={[{ required: false, message: "不能为空" }]}
              trigger="onConfirm"
            >
              <Picker columns={[leaderList]}>
                {(_, actions) => (
                  <>
                    {getFieldValue("takeDepartment") ? (
                      <span
                        className={`fontsize_14 fw_400 color_333`}
                        onClick={actions.open}
                      >
                        {getFieldValue("takeDepartment")}
                      </span>
                    ) : (
                      <span
                        className={`fontsize_14 fw_500 color_666`}
                        onClick={actions.open}
                      >
                        请选择
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </>
                )}
              </Picker>
            </Form.Item>
          )}
        </Form.Item>
        <Form.Item
          name="takeLeader"
          label="带队人"
          rules={[{ required: false, message: "带队人不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          name="constructTime"
          label="建设起止年限"
          rules={[{ required: false, message: "建设起止年限不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.startTime !== curValues.startTime
          }
          noStyle
        >
          {() => (
            <Form.Item
              name="startTime"
              label="计划开工时间"
              rules={[
                {
                  required: false,
                  message: "计划开工时间不能为空",
                },
              ]}
              trigger="onConfirm"
              onClick={() => setStartTimeVisible(true)}
            >
              <DatePicker
                // precision="month"
                visible={startTimeVisible}
                onClose={() => setStartTimeVisible(false)}
              >
                {(value, actions) => (
                  <>
                    {value ? (
                      <span
                        className={`fontsize_14 fw_400 color_333`}
                        onClick={actions.open}
                      >
                        {dayjs(value).format("YYYY-MM-DD")}
                      </span>
                    ) : (
                      <span className={`fontsize_14 fw_500 color_666`}>
                        请选择
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </>
                )}
              </DatePicker>
            </Form.Item>
          )}
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          name="projectName"
          label="挖掘项目"
          rules={[{ required: false, message: "挖掘项目不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.predictTime !== curValues.predictTime
          }
          noStyle
        >
          {() => (
            <Form.Item
              name="predictTime"
              label="计划入库时间"
              rules={[
                {
                  required: false,
                  message: "计划入库时间不能为空",
                },
              ]}
              trigger="onConfirm"
              onClick={() => setWarehousingTimeVisible(true)}
            >
              <DatePicker
                // precision="month"
                visible={warehousingTimeVisible}
                onClose={() => setWarehousingTimeVisible(false)}
              >
                {(value, actions) => (
                  <>
                    {value ? (
                      <span
                        className={`fontsize_14 fw_400 color_333`}
                        onClick={actions.open}
                      >
                        {dayjs(value).format("YYYY-MM-DD")}
                      </span>
                    ) : (
                      <span className={`fontsize_14 fw_500 color_666`}>
                        请选择
                      </span>
                    )}
                    <img src={rightArrow} style={{ width: "20px" }} />
                  </>
                )}
              </DatePicker>
            </Form.Item>
          )}
        </Form.Item>
        <Form.Item
          name="predictTotalInvest"
          label="预计总投资额(万元)"
          rules={[{ required: false, message: "预计总投资额(万元)不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="yearPredictInvest"
          label="2023年预计纳统额(万元)"
          rules={[
            { required: false, message: "2023年预计纳统额(万元)不能为空" },
          ]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}></span>
        </Form.Header>

        <Form.Item
          name="followPeople"
          label="跟进人"
          rules={[{ required: false, message: "跟进人不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>
        <Form.Item
          name="followPeopleContact"
          label="跟进人联系方式"
          rules={[{ required: false, message: "跟进人联系方式不能为空" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Header>
          <span className={`fontsize_14 fw_500 color_333`}>走访照片</span>
        </Form.Header>

        <Form.Item
          shouldUpdate={(prevValues, curValues) =>
            prevValues.imgUrls !== curValues.imgUrls
          }
          noStyle
        >
          {({ getFieldValue }) => (
            <Form.Item
              name="imgUrls"
              label="上传图片"
              rules={[
                {
                  required: false,
                  message: "上传图片不能为空",
                },
              ]}
            >
              <div
                className={`${Styles.upload_btn} ${
                  !!detailData?.imgUrls?.length ? "mb_10" : ""
                }`}
                // onClick={() => {
                //   form.setFieldsValue({
                //     imgUrls: [
                //       "https://img1.baidu.com/it/u=422078137,1307526884&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1689872400&t=23915a3707a4b4d0a92fef85266e4f4f",
                //       "https://img1.baidu.com/it/u=422078137,1307526884&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1689872400&t=23915a3707a4b4d0a92fef85266e4f4f",
                //     ],
                //   });
                // }}
              >
                <FormUpload
                  accept="image/*"
                  data={{ maxNum: 2, uploadText: "上传", unit: "张" }}
                  onUpdate={(value: any, key: any) => {
                    console.log("val-key------", value, key);
                    const imgList = [...(detailData?.imgUrls ?? []), ...value];
                    setDetailData({
                      ...detailData,
                      imgUrls: imgList,
                    });
                    form.setFieldsValue({
                      imgUrls: imgList,
                    });
                  }}
                  model={detailData}
                />
              </div>

              {getFieldValue("imgUrls") &&
                getFieldValue("imgUrls").map((item: string, i: number) => (
                  <div className={Styles.img_view}>
                    <Image
                      src={item}
                      width="100%"
                      className={`${
                        i !== getFieldValue("imgUrls").length - 1 ? "mb_10" : ""
                      }`}
                    />
                    <CloseCircleOutline
                      className={Styles.close_img_btn}
                      onClick={() => {
                        const imgList = [...(detailData?.imgUrls ?? [])];
                        imgList.splice(i, 1);
                        setDetailData({ ...detailData, imgUrls: imgList });
                        form.setFieldsValue({
                          imgUrls: imgList,
                        });
                      }}
                    />
                  </div>
                ))}
            </Form.Item>
          )}
        </Form.Item>
      </Form>
    </>
  );
};
export default Index;
